package com.tool.emulator.apple2.ui;

import com.tool.emulator.apple2.Apple2;

import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.InputStream;

/**
 * CharRom.java @author tl 2011-6-22
 */
public class CharRom {
	private static final int[][][] charBits = new int[256][8][7];
	private static volatile BufferedImage[] charImages = null;

	static {
		byte[] data = loadData();
		if (data != null) {
			BufferedImage[] imgs = new BufferedImage[256];
			for (int i = 0; i < 128; i++) {
				BufferedImage[] ar = createImage(data, i * 8);
				imgs[i] = ar[0];
				imgs[i + 128] = ar[1];
				createPoints(charBits[i + 128], data, i * 8, false);
				createPoints(charBits[i], data, i * 8, true);
			}
			charImages = imgs;
//            charBits[0x60] = charBits[0xff];
			//          charBits[0xE0] = charBits[0xA0];
		}
	}

	public static byte[] loadData() {
		try {
			byte[] data = new byte[1024];
			InputStream in = CharRom.class.getResourceAsStream(Apple2.APPLEIIE ? "chars.bin" : "charrom.bin");
			try {
				new DataInputStream(in).readFully(data);
				return data;
			} finally {
				in.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private static BufferedImage[] createImage(byte[] data, int off) {
		BufferedImage img = new BufferedImage(7, 8, BufferedImage.TYPE_INT_RGB);
		BufferedImage rev = new BufferedImage(7, 8, BufferedImage.TYPE_INT_RGB);
		for (int i = 0; i < 8; i++) {
			int v = data[off++];
			for (int j = 0; j < 7; j++) {
				v >>>= 1;
				if ((v & 1) != 0)
					img.setRGB(j, i, -1);
				else
					rev.setRGB(j, i, -1);
			}
		}
		return new BufferedImage[]{img, rev};
	}

	private static void createPoints(int[][] ar, byte[] data, int off, boolean rev) {
		for (int i = 0; i < 8; i++) {
			int v = data[off++];
			for (int j = 0; j < 7; j++) {
				v >>>= 1;
				if ((v & 1) == 0 == rev)
					ar[i][j] = 0xffffffff;
				else
					ar[i][j] = 0xff000000;
			}
		}
	}

	public static BufferedImage getCharImage(int index) {
		//if(index>=0) return null;
		BufferedImage[] imgs = charImages;
		return imgs == null ? null : imgs[index];
	}

	public static int[][] getCharBits(int index) {
		return charBits[index];
	}
}
